;(function (window, $, undefined) {
    "use strict";

    var analyticsPlugin;
    var eventName = 'not set';

    function setEventName(name) {
        eventName = name;
    }

    function getEventName() {
        return eventName;
    }

    /**
     * 获取当前unix时间戳
     * @returns {number}
     */
    function getClientTime() {
        return Math.round(new Date().getTime() / 1000);
    }

    /**
     * 页面title
     * @returns {string}
     */
    function getPageTitle() {
        return window.document.title;
    }

    /**
     * 页面URL
     * @returns {string}
     */
    function getPageUrl() {
        return window.location.href;
    }

    /**
     * 上一个页面URL
     * @returns {string}
     */
    function getPageReferrer() {
        return window.document.referrer;
    }

    /**
     * 用户唯一标识,类似UV
     * @returns {*}
     */
    function getDistinctId() {
        return window.Param.uuid;
    }

    /**
     * SDK名字
     * @returns {string}
     */
    function getSDKName() {
        return 'js';
    }

    /**
     * SDK版本
     * @returns {string}
     */
    function getSDKVersion() {
        return '1.0';
    }

    /**
     * 获取用户ID
     * @returns {*}
     */
    function getUid() {
        return window.Param.uid;
    }

    /**
     * 获得屏幕宽度
     * @returns {number}
     */
    function screenWidth() {
        return window.screen.width;
    }

    /**
     * 获得屏幕高度
     * @returns {number}
     */
    function screenHeight() {
        return window.screen.height;
    }

    /**
     * 客户端类型
     * @returns {number}
     */
    function getClientType() {
        return 0;
    }

    /**
     * 获得浏览器类型
     * @returns {string}
     */
    function getBrowser() {
        var browser = {};
        var userAgent = navigator.userAgent.toLowerCase();
        var s;
        (s = userAgent.match(/msie ([\d.]+)/)) ? browser.ie = s[1] :
            (s = userAgent.match(/firefox\/([\d.]+)/)) ? browser.firefox = s[1] :
                (s = userAgent.match(/chrome\/([\d.]+)/)) ? browser.chrome = s[1] :
                    (s = userAgent.match(/opera.([\d.]+)/)) ? browser.opera = s[1] :
                        (s = userAgent.match(/version\/([\d.]+).*safari/)) ? browser.safari = s[1] : 0;
        if (browser.ie) {
            return 'ie';
        }

        if (browser.chrome) {
            return 'chrome';
        }

        if (browser.opera) {
            return 'opera';
        }

        if (browser.safari) {
            return 'safari';
        }

        if (browser.firefox) {
            return 'firefox';
        }

        return 'unknown';
    }

    /**
     * 利用原生Js获取操作系统
     * @returns {string}
     */
    function getOS() {
        var sUserAgent = navigator.userAgent;
        var isMac = (navigator.platform == "Mac68K") || (navigator.platform == "MacPPC") || (navigator.platform == "Macintosh") || (navigator.platform == "MacIntel");
        if (isMac) {
            return "Mac";
        }

        var isWin = (navigator.platform == "Win32") || (navigator.platform == "Windows");
        if (isWin) {
            var isWin2K = sUserAgent.indexOf("Windows NT 5.0") > -1 || sUserAgent.indexOf("Windows 2000") > -1;
            if (isWin2K) {
                return "Win2000";
            }
            var isWinXP = sUserAgent.indexOf("Windows NT 5.1") > -1 || sUserAgent.indexOf("Windows XP") > -1;
            if (isWinXP) {
                return "WinXP";
            }
            var isWin2003 = sUserAgent.indexOf("Windows NT 5.2") > -1 || sUserAgent.indexOf("Windows 2003") > -1;
            if (isWin2003) {
                return "Win2003";
            }
            var isWinVista = sUserAgent.indexOf("Windows NT 6.0") > -1 || sUserAgent.indexOf("Windows Vista") > -1;
            if (isWinVista) {
                return "WinVista";
            }
            var isWin7 = sUserAgent.indexOf("Windows NT 6.1") > -1 || sUserAgent.indexOf("Windows 7") > -1;
            if (isWin7) {
                return "Win7";
            }
            var isWin10 = sUserAgent.indexOf("Windows NT 10") > -1 || sUserAgent.indexOf("Windows 10") > -1;
            if (isWin10) {
                return "Win10";
            }
        }

        var isLinux = (String(navigator.platform).indexOf("Linux") > -1);
        if (isLinux) {
            return "Linux";
        }

        var isUnix = (navigator.platform == "X11") && !isWin && !isMac;
        if (isUnix) {
            return "Unix";
        }
        return "other";
    }

    /**
     * 获得浏览器版本
     * @returns {string|*}
     */
    function getBrowserVersion() {
        var browser = {};
        var userAgent = navigator.userAgent.toLowerCase();
        var s;
        (s = userAgent.match(/msie ([\d.]+)/)) ? browser.ie = s[1] :
            (s = userAgent.match(/firefox\/([\d.]+)/)) ? browser.firefox = s[1] :
                (s = userAgent.match(/chrome\/([\d.]+)/)) ? browser.chrome = s[1] :
                    (s = userAgent.match(/opera.([\d.]+)/)) ? browser.opera = s[1] :
                        (s = userAgent.match(/version\/([\d.]+).*safari/)) ? browser.safari = s[1] : 0;
        if (browser.ie) {
            return browser.ie;
        }

        if (browser.firefox) {
            return browser.firefox;
        }

        if (browser.chrome) {
            return browser.chrome;
        }

        if (browser.opera) {
            return browser.opera;
        }

        if (browser.safari) {
            return browser.safari;
        }
        return 'unknown';
    }

    function hukeStatisticsTranscoding() {

        var _utf8_encode, _utf8_decode;
        // private property
        var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

        // private method for UTF-8 encoding
        _utf8_encode = function (string) {
            string = string.replace(/\r\n/g, "\n");
            var utftext = "";
            for (var n = 0; n < string.length; n++) {
                var c = string.charCodeAt(n);
                if (c < 128) {
                    utftext += String.fromCharCode(c);
                } else if ((c > 127) && (c < 2048)) {
                    utftext += String.fromCharCode((c >> 6) | 192);
                    utftext += String.fromCharCode((c & 63) | 128);
                } else {
                    utftext += String.fromCharCode((c >> 12) | 224);
                    utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                    utftext += String.fromCharCode((c & 63) | 128);
                }

            }
            return utftext;
        };

        // private method for UTF-8 decoding
        _utf8_decode = function (utftext) {
            var c, c1, c2, c3;
            var string = "";
            var i = 0;
            c = c1 = c2 = 0;
            while (i < utftext.length) {
                c = utftext.charCodeAt(i);
                if (c < 128) {
                    string += String.fromCharCode(c);
                    i++;
                } else if ((c > 191) && (c < 224)) {
                    c2 = utftext.charCodeAt(i + 1);
                    string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                    i += 2;
                } else {
                    c2 = utftext.charCodeAt(i + 1);
                    c3 = utftext.charCodeAt(i + 2);
                    string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                    i += 3;
                }
            }
            return string;
        };

        // public method for encoding
        this.encode = function (input) {
            var output = "";
            var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
            var i = 0;
            input = _utf8_encode(input);
            while (i < input.length) {
                chr1 = input.charCodeAt(i++);
                chr2 = input.charCodeAt(i++);
                chr3 = input.charCodeAt(i++);
                enc1 = chr1 >> 2;
                enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
                enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
                enc4 = chr3 & 63;
                if (isNaN(chr2)) {
                    enc3 = enc4 = 64;
                } else if (isNaN(chr3)) {
                    enc4 = 64;
                }
                output = output +
                    _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
                    _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
            }
            return output;
        };

        // public method for decoding
        this.decode = function (input) {
            var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
            var i = 0;
            var output = "";
            input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
            while (i < input.length) {
                enc1 = _keyStr.indexOf(input.charAt(i++));
                enc2 = _keyStr.indexOf(input.charAt(i++));
                enc3 = _keyStr.indexOf(input.charAt(i++));
                enc4 = _keyStr.indexOf(input.charAt(i++));
                chr1 = (enc1 << 2) | (enc2 >> 4);
                chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
                chr3 = ((enc3 & 3) << 6) | enc4;
                output = output + String.fromCharCode(chr1);
                if (enc3 !== 64) {
                    output = output + String.fromCharCode(chr2);
                }
                if (enc4 !== 64) {
                    output = output + String.fromCharCode(chr3);
                }
            }
            output = _utf8_decode(output);
            return output;
        };
    }

    analyticsPlugin = {
        configParams: {
            analyticsUrl: 'https://analytics.huke88.com/sa.gif'
        },
        statisticsBaseData: function () {
            return {
                time: getClientTime(),
                page_title: getPageTitle(),
                url: getPageUrl(),
                referrer: getPageReferrer(),
                distinct_id: getDistinctId(),
                lib: getSDKName(),
                lib_version: getSDKVersion(),
                event_name: getEventName(),
                uid: getUid(),
                model: getOS(),
                os: getOS(),
                os_version: getOS(),
                screen_height: screenHeight(),
                screen_width: screenWidth(),
                wifi: 'unknown',
                browser: getBrowser(),
                browser_version: getBrowserVersion(),
                client_type:getClientType(),
                carrier: 'unknown',
                network_type: 'unknown',
                from: Param.channel_from,
                keyword: Param.channel_keyword,
                regd: parseInt(Param.regd ? Param.regd : 0),
                route: Url.spmprefix,
                uuid: Param.uuid,
                uv: Param.uv_id,
                session_id: Param.sid,
                unique_page_id: Param.unique_id,
                vip: parseInt(Param.is_vip ? Param.is_vip : 0),
            };
        },
        uploadStatisticsData: function (uploadData, uploadTime, uploadTable) {
            var _this = this;
            var jsonString = JSON.stringify(uploadData);
            var hukeStatisticsTranscodingar = new hukeStatisticsTranscoding();
            var data = hukeStatisticsTranscodingar.encode(jsonString);

            $.get(_this.configParams.analyticsUrl, {
                "d": data,
                "time": uploadTime,
                "t": uploadTable
            }, function () {
            });
        },
        statisticsPlayVideoProgress: function (options) { //视频播放上报打点数据
            var _this = this;

            setEventName('play_video_progress');
            var statisticsBaseData = _this.statisticsBaseData();
            $.extend(statisticsBaseData, options);
            _this.uploadStatisticsData(statisticsBaseData, statisticsBaseData.time, 'nginxlogs');
        },
        statisticsPageVisit: function (options) { //页面访问记录上报数据
            var _this = this;

            setEventName('page_visit');
            var statisticsBaseData = _this.statisticsBaseData();
            $.extend(statisticsBaseData, options);

            _this.uploadStatisticsData(statisticsBaseData, statisticsBaseData.time, 'nginxlogs');
        },
        statisticsClickEvent: function (options) { //点击行为上报数据
            var _this = this;

            setEventName('click_event');
            var statisticsBaseData = _this.statisticsBaseData();
            $.extend(statisticsBaseData, options);
            _this.uploadStatisticsData(statisticsBaseData, statisticsBaseData.time, 'nginxlogs');
        },
        noteSaveEvent: function (options) { //笔记保存事件上报数据
            var _this = this;

            setEventName('note_save_event');
            var statisticsBaseData = _this.statisticsBaseData();
            $.extend(statisticsBaseData, options);
            _this.uploadStatisticsData(statisticsBaseData, statisticsBaseData.time, 'nginxlogs');
        },
        pupupShowEvent: function (options) { //弹窗展示事件上报数据
            var _this = this;

            setEventName('popup_event');
            var statisticsBaseData = _this.statisticsBaseData();
            $.extend(statisticsBaseData, options);
            _this.uploadStatisticsData(statisticsBaseData, statisticsBaseData.time, 'nginxlogs');
        }
    };

    window.hukeStatistics = analyticsPlugin;
})(window, $);
